{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a0b0075e-6fb5-4fae-a304-9288bbdd366e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import jieba\n",
    "from tqdm import tqdm\n",
    "from gensim import corpora, models, similarities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "56abe5ae-e10e-4911-bf55-a4bb3c6e6da2",
   "metadata": {},
   "outputs": [],
   "source": [
    "in_path = '/home/ljw22/workspace/qwen/MUSER-main/cases_pool.json'\n",
    "out_path = '/home/ljw22/workspace/qwen/MUSER-main/tfidf_top100.json'\n",
    "\n",
    "in_file = open(in_path, 'r', encoding='utf-8')\n",
    "cases_pool = json.load(in_file)\n",
    "\n",
    "corpus_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/corpus.json'\n",
    "corpus_file = open(corpus_path, 'r', encoding='utf-8')\n",
    "raw_corpus = json.load(corpus_file)\n",
    "\n",
    "stopword_path = '/home/ljw22/workspace/qwen/MUSER-main/data/utils/stopword.txt'\n",
    "stopword_file = open(stopword_path, 'r', encoding='utf-8')\n",
    "lines = stopword_file.readlines()\n",
    "stopwords = [i.strip() for i in lines]\n",
    "stopwords.extend(['.','（','）','-', '', '【', '】'])\n",
    "\n",
    "train_test_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/train_test.json'\n",
    "train_test_file = open(train_test_path, 'r')\n",
    "train_test = json.load(train_test_file)\n",
    "test_querys = train_test['train'] + train_test['test']\n",
    "\n",
    "qc_pairs_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/cands_by_query.json'\n",
    "qc_pairs_file = open(qc_pairs_path, 'r')\n",
    "qc_pairs = json.load(qc_pairs_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6631fc65-02a3-4dde-8b29-9cbb4ab95307",
   "metadata": {},
   "outputs": [],
   "source": [
    "dictionary = corpora.Dictionary(raw_corpus)\n",
    "corpus = [dictionary.doc2bow(i) for i in raw_corpus]\n",
    "tfidf = models.TfidfModel(corpus)\n",
    "num_features = len(dictionary.token2id.keys())\n",
    "index = similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=num_features)\n",
    "\n",
    "tfidf_top100 = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1a53e624-ca18-4e31-b9a9-2bb37d7cc2d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...                                                           | 0/100 [00:00<?, ?it/s]\n",
      "Loading model from cache /tmp/jieba.cache\n",
      "Loading model cost 0.811 seconds.\n",
      "Prefix dict has been built successfully.\n",
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:08<00:00, 11.86it/s]\n"
     ]
    }
   ],
   "source": [
    "for qid in tqdm(test_querys):\n",
    "    sim_scores = []\n",
    "    query_text = ''\n",
    "    for part in ['本院查明', '本院认为']:\n",
    "        for sent in cases_pool[qid]['content'][part]:\n",
    "            query_text += sent\n",
    "    query_jieba = jieba.cut(query_text, cut_all=False)\n",
    "    query_tmp = ' '.join(query_jieba).split()\n",
    "    query_cutted = [w for w in query_tmp if w not in stopwords]\n",
    "    query_vec = dictionary.doc2bow(query_cutted)\n",
    "    sim = index[tfidf[query_vec]]\n",
    "    for idx, score in zip(cases_pool.keys(), sim):\n",
    "        i = int(idx)\n",
    "        if qid == i or i not in qc_pairs[qid]:\n",
    "        # if int(qid) == i:\n",
    "            continue\n",
    "        sim_scores.append((idx, score))\n",
    "    # assert len(sim_scores) == 100\n",
    "    sim_scores.sort(key=lambda x:x[1], reverse=True)\n",
    "    # print(sim_scores)\n",
    "    cnt = 0\n",
    "    tfidf_top100[qid] = []\n",
    "    for idx, score in sim_scores:\n",
    "        if cnt >= 100:\n",
    "            break\n",
    "        tfidf_top100[qid].append(idx)\n",
    "        cnt += 1\n",
    "    assert len(tfidf_top100[qid]) == 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3f511058-46b9-44b3-a376-5a8defe397e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e3e7c02e-b2dd-418e-a005-252a818d5706",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b2d417fb-f517-41d4-89b4-bc3886520797",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4024"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(sim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04e201ba-10ce-486b-bc01-7b5ef00d9a9a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
